<template>
    <div id='goods_putaway'>
      <Row type='flex' justify='center' style="padding:60px 100px">
        <Col style="width: 1000px;">
          <Steps :current="current">
            <Step title="完善商品信息"
                  class="prev"></Step>
            <Step title="录入价格信息"
                  class="prev"></Step>
            <Step title="完成上架"
                  class="complate"></Step>
          </Steps>
        </Col>
      </Row>
      <div class="common-style level1" style="width: 900px" v-show='current === 0'>
        <div class="guide">
          <p></p>
          <span>商品信息</span>
        </div>
        <Form inline ref="formValidate1" :model="formValidate1" :rules="ruleValidate1" :label-width="110" style="width: 900px;">
          <FormItem label="门店名称：" prop="shopName" style="display: block;">
            <Input :value="formValidate1.shopName" placeholder="请输入" class="input-width" disabled></Input>
          </FormItem>
          <FormItem label="所属类型：" prop="relateType">
            <Input :value="formValidate1.relateType" placeholder="请输入" class="input-width" disabled></Input>
          </FormItem>
          <FormItem label="营业项分类：" prop="matchClassify" :label-width='180'>
            <Input :value="formValidate1.matchClassify" placeholder="请输入" class="input-width" disabled></Input>
          </FormItem>
          <FormItem label="商品分类：" prop="involvedType" style="display: block;">
            <Input v-model="formValidate1.involvedType[0]" placeholder="请输入" style="width: 120px" disabled></Input>
            <span style="color:#DCDEE2;margin: 0 9px">-</span>
            <Input v-model="formValidate1.involvedType[1]" placeholder="请输入" style="width: 120px" disabled></Input>
          </FormItem>
          <FormItem label="零售商品：" prop="exchangeGoods">
            <Button @click="addProduct">添加商品+</Button>
          </FormItem>
          <FormItem label="所选商品：" prop="selectGoods">
            <Table :columns="columns" :data="formValidate1.selectGoods">
              <template slot-scope="{ row }" slot="action">
                <i class="iconsys icondel" title="删除" @click='delSelect'></i>
              </template>
              <template slot-scope="{ row }" slot="iconPath">
                <div style="margin: 15px 0;">
                  <img :src="row.thumbnail ? row.thumbnail: defaultUrl" alt="" style="width: 90px;height: 60px;display: block;">
                </div>
              </template>
              <template slot-scope="{ row }" slot="goodsUnit">
                <span>{{row.goodsUnit === 0 ? '个' : row.goodsUnit === 1 ? '枚' : row.goodsUnit === 2 ? '份' : ''}}</span>
              </template>
            </Table>
          </FormItem>
          <FormItem>
            <div style="margin-top: 20px">
              <Button type="primary" @click="submitStep1">下一步，录入价格信息</Button>
            </div>
          </FormItem>
        </Form>
        <drawer-commodity
        :selectList='formValidate1.selectGoods'
        :title='title'
        :type='type'
        :value='drawShow'
        :matchClassify='formValidate1.matchClassify'
        @sureSelect='sureSelect' @closeDraw='closeDraw'></drawer-commodity>
      </div>
      <div class="common-style level2" style="width: 900px" v-show='current === 1'>
        <div class="guide">
          <p></p>
          <span>价格信息</span>
        </div>
        <Form inline ref="formValidate2" :model="formValidate2" :rules="ruleValidate2" :label-width="110" style="width: 900px;">
          <FormItem label="销售渠道：" prop="channel" style="display: block;">
            <Input placeholder="请输入" v-model='formValidate2.channel' class="input-width" disabled></Input>
          </FormItem>
          <FormItem label="副标题：" prop="title">
            <Input placeholder="请输入" v-model='formValidate2.title' class="input-width" :maxlength='24'></Input>
          </FormItem>
          <FormItem label="可售库存：" prop="inventory" :label-width="180">
            <Input placeholder="请输入" v-model='formValidate2.inventory' :maxlength='6' class="input-width" :disabled="notControl" @on-keyup="filterNum('inventory')" @on-blur="filterNum('inventory')"></Input>
          </FormItem>
          <Checkbox v-model="notControl" style="margin: 7px 0 0 10px">不限</Checkbox>
          <FormItem label="平台价：" prop="platformPrice" style="display: block;">
            <Input placeholder="请输入" v-model='formValidate2.platformPrice' :maxlength="7" class="input-width" @on-blur="priceBlur" @on-keyup="changeprice"></Input>
          </FormItem>
          <FormItem label="上架时间：" prop="upTime">
            <DatePicker :value="formValidate2.upTime" type="datetime" :editable="false" placeholder="请选择" class="input-width" @on-change="activityStartChange" :options="activityStartOptions"></DatePicker>
          </FormItem>
          <FormItem label="下架时间：" prop="downTime" :label-width="180">
            <DatePicker :value="formValidate2.downTime" type="datetime" :editable="false" placeholder="请选择" class="input-width" @on-change="activityEndChange" :options="activityEndOptions"></DatePicker>
          </FormItem>
          <FormItem style="margin-top: 20px;">
            <Button class="system-submit-btn" style="color: #2D8CF0;" @click='skipStep1'>上一步，完善商品信息</Button>
            <Button type="primary" class="system-submit-btn" style="margin-left: 15px" @click='submitStep2'>下一步，完成商品上下架</Button>
          </FormItem>
        </Form>
      </div>
      <div class="common-style level3" style="width: 900px;text-align: center;padding-top:50px" v-show='current === 2'>
        <div style="color: #18BE6B;">
          <Icon type="ios-checkmark-circle-outline" size='35' />
        </div>
          <h3 style="margin: 10px 0 50px 0">完成上架({{timeNum}})s</h3>
          <Button type="primary" @click="goBackList">返回兑换商品列表</Button>
      </div>
    </div>
  </template>

<script>
import DrawerCommodity from '@/view/components/drawer-commodity/index.vue'
import { retailGoodsUp } from '@/api/commondity/index'
import { mapState } from 'vuex'
import { routeEqual } from '@/libs/util'
export default {
  name: 'goods_putaway',
  components: { DrawerCommodity },
  computed: {
    ...mapState({
      merchantId: state => state.user.merchantId,
      userId: state => state.user.userId,
      userName: state => state.user.userName
    })
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      if (vm.shopId !== to.query.shopId) {
        vm.shopId = to.query.shopId
        vm.shopName = to.query.shopName
        vm.current = 0
      }
    })
  },
  watch: {
    'notControl' (val) {
      if (val) {
        this.ruleValidate2.inventory.required = false
        this.formValidate2.inventory = ''
        this.$refs.formValidate2.validateField('inventory')
      } else {
        this.ruleValidate2.inventory.required = true
      }
    },
    'formValidate1.selectGoods' (val) {
      if (val.length > 0) {
        this.formValidate1.involvedType = [val[0].parentSysCategoryName, val[0].sysCategoryName]
      }
    },
    current (val) {
      if (val === 2) {
        this.timeNum = 3
        this.timer = setInterval(() => {
          this.timeNum--
          if (this.timeNum === 0) {
            clearInterval(this.timer)
            this.handleReset()
          }
        }, 1000)
      }
    }
  },
  data () {
    return {
      submitLock: false,
      timer: '',
      timeNum: 3,
      defaultUrl: require('@/assets/images/default.png'),
      shopId: '',
      shopName: '',
      title: '零售商品列表',
      type: '1',
      drawShow: false,
      notControl: false,
      current: 0,
      matchClassifyList: [],
      exchangeTypeList: [],
      exchangeControlList: [],
      memberControlList: [],
      shopList: [],
      activityStartOptions: {},
      activityEndOptions: {},
      formValidate1: {
        involvedType: [],
        relateType: '',
        matchClassify: '',
        exchangeGoods: '',
        selectGoods: [],
        shopName: ''
      },
      ruleValidate1: {
        involvedType: { required: true, message: '商品分类不能为空', type: 'array', trigger: 'change' },
        relateType: { required: true, message: '所属类型不能为空', trigger: 'change' },
        matchClassify: { required: true, message: '对应分类不能为空', trigger: 'change' },
        shopName: { required: true, message: '门店名称不能为空', trigger: 'change' },
        exchangeGoods: {
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (this.formValidate1.selectGoods.length > 0) {
              callback()
            } else {
              callback(new Error('请选择商品'))
            }
          }
        },
        selectGoods: {
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (this.formValidate1.selectGoods.length > 0) {
              callback()
            } else {
              callback(new Error('所选商品不能为空'))
            }
          }
        }
      },
      formValidate2: {
        channel: '',
        title: '',
        inventory: '',
        platformPrice: '0.00',
        upTime: '',
        downTime: ''
      },
      ruleValidate2: {
        channel: { required: true, message: '销售渠道不能为空', trigger: 'change' },
        title: { required: true, message: '请输入副标题', trigger: 'change' },
        inventory: { required: true, message: '请输入可售库存', trigger: 'change' },
        platformPrice: { required: true, message: '请输入平台价', trigger: 'change' },
        upTime: {
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (!new Date(this.formValidate2.upTime).getTime()) {
              callback(new Error('请选择上架时间'))
            } else if (new Date(this.formValidate2.upTime).getTime() > new Date(this.formValidate2.downTime).getTime() || new Date(this.formValidate2.upTime).getTime() === new Date(this.formValidate2.downTime).getTime()) {
              callback(new Error('上架时间要小于下架时间'))
            } else {
              callback()
            }
          }
        },
        downTime: {
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (!new Date(this.formValidate2.downTime).getTime()) {
              callback(new Error('请选择下架时间'))
            } else if (new Date(this.formValidate2.upTime).getTime() > new Date(this.formValidate2.downTime).getTime() || new Date(this.formValidate2.upTime).getTime() === new Date(this.formValidate2.downTime).getTime()) {
              callback(new Error('下架时间要大于上架时间'))
            } else if (new Date().getTime() > new Date(this.formValidate2.downTime).getTime()) {
              callback(new Error('下架时间要大于当前系统时间'))
            } else {
              callback()
            }
          }
        }
      },
      columns: [
        {
          title: '商品图片',
          slot: 'iconPath'
        },
        {
          title: '商品名称',
          key: 'skuName'
        },
        {
          title: '商品编码',
          key: 'skuId'
        },
        {
          title: '商品条码',
          key: 'barcode'
        },
        {
          title: '单位',
          slot: 'goodsUnit'
        },
        {
          title: '数量',
          key: 'goodsNum'
        },
        {
          title: '操作',
          slot: 'action'
        }
      ]
    }
  },
  methods: {
    changeprice () {
      if (this.formValidate2.platformPrice !== '' && this.formValidate2.platformPrice.substring(0, 1) === '.') {
        this.formValidate2.platformPrice = ''
      }
      this.formValidate2.platformPrice = this.formValidate2.platformPrice.replace(/^0*(0\.|[1-9])/, '$1') // 粘贴不生效
      this.formValidate2.platformPrice = this.formValidate2.platformPrice.replace(/[^\d.]/g, '') // 清除“数字”和“.”以外的字符
      this.formValidate2.platformPrice = this.formValidate2.platformPrice.replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
      this.formValidate2.platformPrice = this.formValidate2.platformPrice.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
      this.formValidate2.platformPrice = this.formValidate2.platformPrice.replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3') // 只能输入两个小数
      if (this.formValidate2.platformPrice.indexOf('.') < 0 && this.formValidate2.platformPrice !== '') { // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        if (this.formValidate2.platformPrice.substring(0, 1) === '0' && this.formValidate2.platformPrice.length === 2) {
          this.formValidate2.platformPrice = this.formValidate2.platformPrice.substring(1, this.formValidate2.platformPrice.length)
        }
      }
      if (this.formValidate2.platformPrice > 9999.99) {
        this.formValidate2.platformPrice = this.formValidate2.platformPrice.substring(0, 4)
      }
    },
    priceBlur () {
      this.formValidate2.platformPrice = this.formValidate2.platformPrice + ''
      this.formValidate2.platformPrice = this.formValidate2.platformPrice.replace(/[^\d.]/g, '')
      if (this.formValidate2.platformPrice === '') {
        this.formValidate2.platformPrice = ''
      } else if (this.formValidate2.platformPrice.indexOf('.') === -1) {
        this.formValidate2.platformPrice = this.formValidate2.platformPrice + '.00'
      } else if (this.formValidate2.platformPrice.indexOf('.')) {
        let ste = this.formValidate2.platformPrice.substring(this.formValidate2.platformPrice.indexOf('.') + 1)
        if (!ste) {
          this.formValidate2.platformPrice = this.formValidate2.platformPrice + '00'
        }
        if (ste.length === 1) {
          this.formValidate2.platformPrice = this.formValidate2.platformPrice + '0'
        } if (ste.length > 2) {
          this.formValidate2.platformPrice = this.formValidate2.platformPrice.substring(0, this.formValidate2.platformPrice.indexOf('.') + 3)
        }
      }
    },
    filterNum (param) {
      this.formValidate2[param] = this.formValidate2[param].replace(/[^\d]/g, '')
      if (this.formValidate2[param].length > 1) {
        this.formValidate2[param] = this.formValidate2[param].replace(/[^\d]/g, '').replace(/^0{1,}/g, '')
      }
    },
    delSelect () {
      this.formValidate1.selectGoods = []
    },
    addProduct () {
      this.drawShow = true
    },
    sureSelect (data) {
      this.formValidate1.selectGoods = []
      this.formValidate1.selectGoods = data
      this.$refs.formValidate1.validate()
    },
    closeDraw () {
      this.drawShow = false
    },
    activityStartChange (time) {
      this.formValidate2.upTime = time
      this.activityEndOptions = {
        disabledDate (date) {
          return date.valueOf() < new Date(time.split(' ')[0]).getTime() - 24 * 3600 * 1000
        }
      }
    },
    activityEndChange (time) {
      this.formValidate2.downTime = time
      this.activityStartOptions = {
        disabledDate (date) {
          return date.valueOf() > new Date(time).getTime()
        }
      }
    },
    next () {
      if (this.current === 2) {
        this.current = 0
      } else {
        this.current += 1
      }
    },
    submitStep1 () {
      this.$refs.formValidate1.validate(valid => {
        if (valid) {
          this.next()
          this.formValidate2.channel = '收银台'
          this.formValidate2.title = this.formValidate1.selectGoods[0].subTitle ? this.formValidate1.selectGoods[0].subTitle : ''
        }
      })
    },
    skipStep1 () {
      this.current--
    },
    submitStep2 () {
      this.$refs.formValidate2.validate(valid => {
        if (valid) {
          if (this.submitLock) {
            return
          }
          this.submitLock = true
          let data = {
            merchantId: this.merchantId,
            channelId: '1', // 1表示收银台
            shopId: this.$route.query.shopId,
            sysGoodsId: this.formValidate1.selectGoods[0].sysGoodsId,
            sysId: this.formValidate1.selectGoods[0].sysId,
            title: this.formValidate2.title,
            thumbnail: this.formValidate1.selectGoods[0].thumbnail ? this.formValidate1.selectGoods[0].thumbnail : '',
            listingAt: this.formValidate2.upTime,
            delistingAt: this.formValidate2.downTime,
            creator: this.userId,
            creatorName: this.userName,
            inventory: this.formValidate2.inventory ? this.formValidate2.inventory : this.notControl ? '-1' : '',
            goodsPrices: [
              {
                priceType: 0,
                priceCategory: 1,
                amount: this.formValidate2.platformPrice
              }
            ]
          }
          retailGoodsUp(data).then(res => {
            this.submitLock = false
            if (res.data.status === 200) {
              this.next()
            } else {
              this.$Message.error(`${res.data.error}`)
            }
          })
        }
      })
    },
    goBackList () {
      this.handleReset()
    },
    handleReset () {
      this.$store.commit('closeTag', this.$route)
      this.$store.commit('setTagNavList', this.$store.state.app.tagNavList.filter(item => !routeEqual(this.$route, item)))
      this.$nextTick(() => {
        this.$router.push({
          name: 'goods_list',
          params: {
            id: this.shopId
          },
          query: {
            shopName: this.shopName
          }
        })
      })
    }
  },
  mounted () {
    this.shopId = this.$route.query.shopId
    this.shopName = this.$route.query.shopName
    this.formValidate1.shopName = this.shopName
    this.formValidate1.relateType = '营业项分类'
    this.formValidate1.matchClassify = '零售商品'
  }
}
</script>

<style lang="less">
#goods_putaway{
  .input-width{
    width: 260px;
  }
  .btn{
    width: 72px;
  }
  .prev {
    width: 43% !important;
  }
  .complate {
    width: 14% !important;
  }
  .common-style{
    margin: 0 auto !important;
  }
  .guide{
    display: flex;
    margin-bottom: 30px;
    p {
      width: 8px;
      height: 20px;
      background: #2d8cf0;
      margin-right: 10px;
    }
  }
  .rich-editor{
    width: 710px;
    .w-e-text-container{
      height: 200px !important;
    }
  }
}
</style>
